import React from 'react';
import ReactDOM from 'react-dom';
import { Menu } from 'antd';
import { DataNode } from 'antd/es/tree';

interface MenuPortalProps {
  menu: {
    visible: boolean;
    x: number;
    y: number;
    node: any;
    type: string;
  } | null;
  menuRef: React.RefObject<HTMLDivElement>;
  getMenuItems: (type: string, node: CmdMaterialSpace.TreeNode) => any[];
  handleMenuClick: (
    commandKey: string,
    node: DataNode & CmdMaterialSpace.TreeNode,
  ) => void;
}

const MenuPortal: React.FC<MenuPortalProps> = ({
  menu,
  menuRef,
  getMenuItems,
  handleMenuClick,
}) => {
  if (!menu?.visible) return null;
  return ReactDOM.createPortal(
    <div
      ref={menuRef}
      style={{
        position: 'fixed',
        left: menu.x,
        top: menu.y,
        zIndex: 9999,
      }}
      onClick={(e) => e.stopPropagation()}
      className='bg-white border rounded shadow-lg min-w-[120px]'
    >
      <Menu
        items={getMenuItems(menu.type, menu.node)}
        onClick={({ key }) => handleMenuClick(key, menu.node)}
      />
    </div>,
    document.body,
  );
};

export default MenuPortal;
